import {createRouter, createWebHistory} from 'vue-router'
import { nextTick } from 'vue'
import { preloadPageData, getCurrentUser, clearExpiredCache, smartPreload } from '@/utils/routePreloader'

// 预加载核心组件
import Manager from '@/views/Manager.vue'
import Home from '@/views/manager/Home.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: Manager, // 主布局直接导入
      redirect: '/home',
      children: [
        { 
          path: 'home', 
          name: 'Home',
          component: Home, // 首页直接导入
          meta: { preload: true, title: '系统首页' }
        },
        {
          path: 'knowledge',
          name: 'Knowledge',
          component: () => import(
            /* webpackChunkName: "knowledge" */
            /* webpackPrefetch: true */
            '@/views/manager/Knowledge/Knowledge.vue'
          ),
          meta: { preload: true, title: '知识管理' }
        },
        {
          path: 'knowledge/space/:spaceId',
          name: 'SpaceDetail',
          component: () => import(
            /* webpackChunkName: "knowledge-detail" */
            /* webpackPrefetch: true */
            '@/views/manager/Knowledge/SpaceDetail.vue'
          ),
          meta: { preload: true, title: '知识空间详情' }
        },
        {
          path: 'knowledge/space/:spaceId/document/:documentId/edit',
          name: 'DocumentEditor',
          component: () => import(
            /* webpackChunkName: "document-editor" */
            /* webpackPreload: true */
            '@/views/manager/Knowledge/DocumentEditor.vue'
          ),
          meta: { preload: true, title: '文档编辑' }
        },
        {
          path: 'knowledge/space/:spaceId/document/:documentId',
          redirect: to => {
            return `/knowledge/space/${to.params.spaceId}/document/${to.params.documentId}/preview`
          }
        },
        {
          path: 'knowledge/space/:spaceId/document/:documentId/preview',
          name: 'DocumentPreview',
          component: () => import(
            /* webpackChunkName: "document-preview" */
            /* webpackPrefetch: true */
            '@/views/manager/Knowledge/DocumentPreview.vue'
          ),
          meta: { preload: true, title: '文档预览' }
        },
        {
          path: 'knowledge/search',
          name: 'AdvancedSearch',
          component: () => import(
            /* webpackChunkName: "advanced-search" */
            /* webpackPrefetch: true */
            '@/views/manager/Knowledge/AdvancedSearch.vue'
          ),
          meta: { preload: true, title: '高级搜索' }
        },
        { 
          path: 'projects', 
          name: 'ProjectList',
          component: () => import(
            /* webpackChunkName: "projects" */
            /* webpackPrefetch: true */
            '@/views/manager/ProjectList.vue'
          ),
          meta: { preload: false, title: '项目管理' }
        },
        { 
          path: 'projects/:id', 
          name: 'ProjectDetail',
          component: () => import('@/views/manager/ProjectDetail.vue'), 
          props: true,
          meta: { preload: false, title: '项目详情' }
        },
        { 
          path: 'person', 
          name: 'Person',
          component: () => import('@/views/manager/Person.vue'),
          meta: { preload: false, title: '个人资料' }
        },
        { 
          path: 'password', 
          name: 'Password',
          component: () => import('@/views/manager/Password.vue'),
          meta: { preload: false, title: '修改密码' }
        },
        { 
          path: 'group', 
          name: 'Group',
          component: () => import('@/views/manager/Group.vue'),
          meta: { preload: false, title: '小组管理' }
        }
      ]
    },
    { 
      path: '/login', 
      name: 'Login',
      component: () => import('@/views/Login.vue'),
      meta: { title: '用户登录' }
    },
    { 
      path: '/register', 
      name: 'Register',
      component: () => import('@/views/Register.vue'),
      meta: { title: '用户注册' }
    },
  ]
})

// 应用启动时的智能预加载
let hasInitialPreload = false
const performInitialPreload = async () => {
  if (hasInitialPreload) return
  hasInitialPreload = true
  
  // 延迟执行智能预加载，避免阻塞首屏渲染
  setTimeout(async () => {
    await smartPreload()
    // 定期清理过期缓存
    setInterval(clearExpiredCache, 10 * 60 * 1000) // 每10分钟清理一次
  }, 1000)
}

// 路由守卫 - 预加载逻辑
router.beforeEach(async (to, from, next) => {
  // 执行初始预加载（仅首次）
  performInitialPreload()
  
  // 设置页面标题
  if (to.meta?.title) {
    document.title = `${to.meta.title} - 团队小助手`
  }

  try {
    // 用户认证检查
    const user = JSON.parse(localStorage.getItem('system-user') || '{}')
    if (to.path !== '/login' && to.path !== '/register' && !user?.phone) {
      next('/login')
      return
    }

    // 预加载页面相关数据
    if (to.meta?.preload) {
      await preloadPageData(to)
    }

    next()
  } catch (error) {
    console.error('路由预加载失败:', error)
    next()
  }
})

// 路由后置守卫 - 清理工作
router.afterEach((to, from) => {
  // 页面切换完成后的清理工作
  nextTick(() => {
    // 可以在这里添加页面切换完成后的逻辑
    console.log(`页面切换完成: ${from.name || 'unknown'} -> ${to.name || 'unknown'}`)
  })
})

export default router
